/*
 * @lc app=leetcode.cn id=144 lang=javascript
 *
 * [144] 二叉树的前序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function (root) {
  const result = [];

  if (root === null) return result;

  let current = root;
  // 通过mostRight.right是否有值来判断是第几次访问每个子树的root节点
  let mostRight = null;

  while (current !== null) {
    mostRight = current.left;
    if (mostRight !== null) {
      while (mostRight.right !== null && mostRight.right !== current) {
        mostRight = mostRight.right;
      }
      if (mostRight.right === null) {
        result.push(current.val);
        mostRight.right = current;
        current = current.left;
        continue;
      } else {
        mostRight.right = null;
      }
    } else {
      result.push(current.val);
    }
    current = current.right;
  }

  return result;
};
// @lc code=end
